/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.webservice.client;

import com.edu.kamai.client.control.scoreControl;
import com.edu.kamai.webservice.score.Score;
import com.edu.kamai.webservice.score.ScoreService;
import com.edu.kamai.webservice.score.ScoreService_Service;

import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;

/**
 *
 * @author xyzhu
 */
public class WSScoreClient {
    private final QName qName = new QName("http://webservice.kamai.edu.com/",
            "scoreService");
    private URL[] url;
    private int size;
    
    public WSScoreClient() throws Exception{
        size = scoreControl.getNetList().size();
        url = new URL[size];
        for(int i=0;i<size;i++){
            url[i] = new URL("http://" + scoreControl.getNetList().get(i) + 
                    "/scoreService/scoreService?WSDL");
        }
    }
    
    public int updateScoreByContestIDAndStudentID(int cID,String uID,
            int scores,int finishTime,int type) throws Exception{
        int ran = (int) (size * Math.random());
        int k = ran;
        boolean find = false;
        Exception ex = null;
        int res = 0;
        do{
            try{
                System.out.println("updateScore : " + url[k]);
                ScoreService_Service service = new ScoreService_Service(url[k], qName);
                ScoreService port = service.getScoreServicePort();
                res = port.updateScoreByContestIDAndStudentID(cID, uID, scores,
                        finishTime, type);
                find = true;
            }catch(Exception e){
                k=(k+1)%size;
                ex = e;
                break;
            }
        }while(k!=ran);
        if(!find){
            throw ex;
        }
        return res;
    }
    
    public List<Score> getScoreByUserID(String uID) throws Exception{
        int ran = (int) (size * Math.random());
        int k = ran;
        boolean find = false;
        Exception ex = null;
        List<Score> res = null;
        do{
            try{
                System.out.println("getScoreByUserID : " + url[k]);
                ScoreService_Service service = new ScoreService_Service(url[k], qName);
                ScoreService port = service.getScoreServicePort();
                res = port.getScoreByUserID(uID);
                find = true;
            }catch(Exception e){
                k=(k+1)%size;
                ex = e;
                break;
            }
        }while(k!=ran);
        if(!find){
            throw ex;
        }
        return res;
    }
    
}
